#!/usr/bin/env python

#extract scores out of flexx log file

from openeye.oechem import *
import sys, string, os

file_name = sys.argv[1] #log file


out_file = open (sys.argv[2], 'w') 

#directory with mol2 files
dir = sys.argv[3]

#----------------------
def score_sort(a,b):
   if a[1] < b[1] :
     return -1
   elif a[1] == b[1]:
     return 0
   else:
     return 1

#----------------------
def match_files2mol_name(dir):
	file_mol_dict = {}
	files = os.listdir(dir)
	for file_name in files:
		if file_name[-4:] == 'mol2':
			mol = OEGraphMol()
			ifs = oemolistream(dir + '/' + file_name)
			OEReadMolecule(ifs, mol)
			moli_name = mol.GetTitle()
			file_mol_dict[file_name[:-5]] = moli_name
			ifs.close()
	return file_mol_dict
     

#----------------------

dict = {}

total_list = []

file_mol_dict = match_files2mol_name(dir)

print '=========> open ' + file_name + ' <==============='
read_file = open(file_name, 'r')
for i in read_file.readlines():
#    print i[0:6]
  if (i[0:8] == 'SELECTED') :
    junk,name = i.split(' --')
    name = name.strip()
    name = file_mol_dict[name]
    #print name
  elif i[3:4] == '1':
    values= i.split('|')	
    total = values[2]
    match = values[3]
    lipo  = values[4]
    ambig  = values[5]
    clash = values[6]
    rot = values[7]
    dict[name] = [total,match,lipo,ambig,clash,rot]
    print dict[name]
    print i

	
read_file.close()
  
content = []

#print dict.keys()

keys = dict.keys()
keys.sort()

out_file.write('name\t' + 'total\tmatch\tlipo\tambig\tclash\trot\n')

for key in keys:
	out_file.write(key)
	for i in range(0,len(dict[key])):
		out_file.write('\t' + dict[key][i])
	out_file.write('\n')

out_file.close()




